<template>
  <div class="login-page">
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label"
          >邮箱地址</label
        >
        <!--地址验证-->
        <!--v-model 是父传子 传值的作用-->
        <vaildate-input
          placeholder="请输入正确的邮箱地址"
          v-model="emailVal"
          :rules="emailRules"
          @value="emailValue"
        >
        </vaildate-input>
      </div>

      <!--密码验证-->
      <div class="mb-3">
        <label for="exampleFormControlTextarea1" class="form-label">密码</label>
        <vaildate-input
          placeholder="请输入密码"
          v-model="passwordVal"
          :rules="passwordRules"
          @value="passwordValue"
        >
        </vaildate-input>
      </div>

      <!-- 插值，插入ValidateForm-->
      <template #submit>
        <span type="submit" class="btn btn-danger">登录</span>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import ValidateForm from "@/components/ValidateForm.vue";
import VaildateInput, { RulesProp } from "@/components/VaildateInput.vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import createMessage from "@/hook/createMessage";

export default defineComponent({
  name: "LoginIndex",
  components: {
    ValidateForm,
    VaildateInput,
  },
  setup() {
    const emailVal = ref("111@test.com");
    //邮箱验证规则
    const emailRules: RulesProp = [
      //这个是邮箱的规则，应该被这个东西所约束
      { type: "required", message: "电子邮箱地址不能为空" }, // 这个是必填项
      { type: "email", message: "请输入正确的邮箱规则" },
    ];

    //密码验证
    const passwordVal = ref("111111");
    const passwordRules: RulesProp = [
      //这个是邮箱的规则，应该被这个东西所约束
      { type: "required", message: "密码不能为空" },
    ];

    //接收子传的值,实现vue3的双向绑定
    const emailValue = (val: string) => {
      emailVal.value = val;
    };
    const passwordValue = (val: string) => {
      passwordVal.value = val;
    };

    // 登录按钮被点击时，接收子组件的参数
    const store = useStore();
    const router = useRouter();
    const onFormSubmit = (result: boolean) => {
      console.log("123", result);
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value,
        };
        store.dispatch("loginAndFecth", payload).then(() => {
          createMessage('登录成功 2 秒后跳转到首页','success')
          setTimeout(()=>{
            //  发送登录
            router.push("/");
          },2000)       
        }).catch(e=>{
          console.log(e);
          
        });
      }
    };

    return {
      emailRules,
      emailVal,
      emailValue,
      onFormSubmit,
      passwordVal,
      passwordRules,
      passwordValue,
    };
  },
});
</script>

<style scoped></style>
